use crate::oss::OssConfig;
use rcmd_core::{lazy_static::lazy_static, log::{self}};
use std::{env::var, path::PathBuf};

pub const PKG_FILE_NAME: &str = "dpm.yml";
pub const ENV_CONFIG: &str = ".dpm_config";
pub const INS_DIR_NAME: &str = "dpms_";

pub struct BaseConfig {
    pub pkg_file_name: String,
}

impl Default for BaseConfig {
    fn default() -> Self {
        Self {
            pkg_file_name: "dpm.yml".to_string(),
        }
    }
}

///app运行全局上下文
pub struct AppContext {
    //api host
    pub uri_base: String,
    pub uri_open: String,
    //store
    pub oss_config: OssConfig,
}

impl AppContext {
    fn get_env_path() -> Option<PathBuf> {
        let env_spath = vec![std::env::current_exe().ok(), std::env::current_dir().ok()];
        for p in env_spath {
            if let Some(e) = p {
                let c: PathBuf = e.parent().unwrap().join(ENV_CONFIG);
                log::debug!("init env with path:{}", &c.display());
                return Some(c);
            }
        }
        None
    }
}

impl Default for AppContext {
    fn default() -> Self {
        // init config
        let env_f  = Self::get_env_path().expect("[config]get env path failed!");
        let c = dotenv::from_path(env_f.clone());
        if c.is_err(){ 
            log::error!("dotenv from file raise error!{:?} path={:?}", c.err(), env_f);
        }
        let uri_base = var("HOST").unwrap_or("UNKNOWN HOST".to_string());
        let mut conf = OssConfig::new(
            var("OSS_ACCESSKEY").unwrap_or("UNKNOWN OSS_ACCESSKEY".to_string()),
            var("OSS_ACCESSSEC").unwrap_or("UNKNOWN OSS_ACCESSSEC".to_string()),
            var("OSS_ENDPOINT").unwrap_or("UNKNOWN OSS_ENDPOINT".to_string()),
            var("OSS_BUCKET").unwrap_or("UNKNOWN OSS_BUCKET".to_string()),
        );

        let oss_path = var("OSS_BUCKET_PATH").unwrap_or("/".to_string());
        conf.set_path(Some(oss_path));
        log::debug!("API host is {:?}", uri_base);
        return Self {
            uri_base: String::from(&uri_base.to_owned()),
            uri_open: format!("https://{}/{}", &uri_base.as_str(), "plugins"),
            oss_config: conf,
        };
    }
}

lazy_static! {
    pub static ref CONTEXT: AppContext = AppContext::default();
}
